package com.tech.service.impl;

import com.tech.mapper.GoodsImageDao;
import com.tech.mapper.factory.DaoImplFactory;
import com.tech.repository.entity.GoodsImage;
import com.tech.repository.session.GoodsSession;
import com.tech.service.GoodsImageService;
import com.tech.util.FileUtil;
import com.tech.view.common.GraphicsUtil;
import com.tech.view.common.ResourcesUtil;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;

public class GoodsImageServiceImpl implements GoodsImageService {
	private GoodsImageDao goodsImageDao = DaoImplFactory.getGoodsImageDao();

	@Override
	public int addGoodsImage(GoodsImage goodsImage) {
		GoodsSession.CURRENT_NEW_IMAGE = goodsImage;
		return goodsImageDao.addGoodsImage(goodsImage);
	}

	/**
	 * 根据商品ID获取该商品的所有图片，默认数量是5，但其实一件商品最多只能添加3张图片
	 *
	 * @param gid 商品编号
	 */
	@Override
	public List<GoodsImage> getGoodsImageListById(int gid) {
		return goodsImageDao.getGoodsImagesList(gid, 5);
	}

	@Override
	public boolean updateGoodsImage(GoodsImage goodsImage) {
		GoodsSession.CURRENT_NEW_IMAGE = goodsImage;
		return goodsImageDao.updateGoodsImage(goodsImage);
	}

	@Override
	public List<GoodsImage> getImage(List<GoodsImage> images, int count, int imageWidth, String dir) {
		if (images.size() == 0) return images;
		images.subList(0, Math.min(images.size(), count))
				.parallelStream()
				.forEach(goodsImage -> {
					// 文件名由gid和修改时间戳拼接
					String filename = "" + goodsImage.getImid() + goodsImage.getUpdateTime() + "." + goodsImage.getSuffix();
					BufferedImage image = ResourcesUtil.getImageByPath(dir + filename);
					if (image == null) { //本地不存在
						image = goodsImageDao.getImageByImid(goodsImage.getImid()).getImage();

						if (imageWidth > 0)// 缩放图片大小
							image = GraphicsUtil.createScaledCompositeInstance(image, imageWidth, false);

						// 缩放后图片保存到本地
						FileUtil.saveImage(image, goodsImage.getSuffix(),
								new File(ResourcesUtil.getAbsolutePathByPath(dir) + filename));
					}
					goodsImage.setImage(image);
				});
		return images;
	}

}
